import React, { Fragment, RefObject, FC, useEffect, useState, useMemo, useRef } from 'react'
import { type ImageUploadItem } from "antd-mobile/es/components/image-uploader";
import { type DetailResult } from "@/pages/types/type";
import { urlPrefix, obsPrifix, postRequestInit } from '@/utils/http';
import { ImageUploader, Space, Button, NoticeBar, Popup, Form } from 'antd-mobile'
import { EditSOutline,AddCircleOutline } from 'antd-mobile-icons';
import { DemoBlock } from '../demos-util';


export const UploadStatus: FC<{ folder: string, accept?:string, onChange?: (items: ImageUploadItem[]) => void | undefined }> = ({ onChange, folder, accept="*.pdf" }) => {

    const [fileList, setFileList] = useState<ImageUploadItem[]>([
        //{ key: 'bbc', url: 'https://images.unsplash.com/photo-1567945716310-4745a6b7844b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60', },
    ])
    // 下面这个上传函数已经没有调用！
    async function mockUpload(file: File) {
        //await sleep(3000)
        const formData = new FormData();
        formData.append('file', file);
        formData.append("username", "Groucho");

        const req: XMLHttpRequest = new XMLHttpRequest();
        req.open("post", `${urlPrefix}/api/file-update/upload`, true/** async */)
        req.onload = (ev: ProgressEvent<EventTarget>) => {
            console.log("onload,lengthComputable=", ev.lengthComputable, ",load=", ev.loaded, ",total=", ev.total)
            console.log(ev);
        }
        req.onprogress = (ev: ProgressEvent<EventTarget>) => {
            console.log("onprogress.lengthComputable=", ev.lengthComputable, ",load=", ev.loaded, ",total=", ev.total)
            console.log(ev);
        }

        req.onloadend = (ev: ProgressEvent<EventTarget>) => {
            console.log("onloadend:lengthComputable=", ev.lengthComputable, ",load=", ev.loaded, ",total=", ev.total)
            console.log(ev);
            return {
                url: URL.createObjectURL(file),
            }
        }
        req.send(formData);
        return {
            url: URL.createObjectURL(file),
        }
    }

    function onImageChange(items: ImageUploadItem[]) {
        setFileList(items);
        onChange?.(items);
    }
    async function UploadByFetch(file: File, folder: string): Promise<ImageUploadItem> {
        const formData = new FormData();
        formData.append('file', file);
        formData.append("folder", folder || "sing-block-file");
        let response = await fetch(`${urlPrefix}/api/file-update/upload`, {
            method: 'POST',
            body: formData
        });

        let result: DetailResult<{ key: string, thumb: string }> = await response.json();
        console.log('result=', result);
        console.log('file=', file);

        const isImage = file.type.startsWith('image');
        return {
            url: isImage ? URL.createObjectURL(file) : `${obsPrifix}/${result.data!.thumb}`,
            thumbnailUrl: isImage ? undefined : `${obsPrifix}/${result.data!.thumb}`,
            key: result.data!.key,
            extra: { 'name': file.name }
        }
    }
    return (
        <ImageUploader
            accept={accept}
            value={fileList}
            onChange={onImageChange}
            upload={(file) => UploadByFetch(file, folder)}
        />
    )
}



export const UploadObjectObsMaterial:  FC<{ title: string, label: string, url: string, source: number | string, onSuccess: () => void }> = ({ title, url, source, label, onSuccess }) => {
        const [ing, setIng] = useState<boolean>(false);
        const [success, setSuccess] = useState<string>();
        const [fail, setFail] = useState<string>();
        const [visible, setVisible] = useState<boolean>(false);
        const [loadFails, setLoadFails] = useState<string[]>([]);
        const [loadOK, setLoadOK] = useState<string | undefined>(undefined);

        // 这里没有定义好！
        type FieldType = { remark: string }

        async function onFinish(values: FieldType) {
            setIng(true);
            setFail(undefined);
            setSuccess(undefined);
            let response: Promise<Response> = fetch(`${urlPrefix}${url}/create/${source}`, postRequestInit({ ...values }))
            response.then((rsp: Response) => {
                console.log(rsp);
                if (rsp.ok) {
                    rsp.json().then((x: DetailResult<number>) => {
                        console.log(x);
                        const { data, code, msg } = x;
                        console.log('history id=', data);
                        if (code === 0) {
                            setSuccess(msg);
                            onSuccess();
                            setVisible(false);
                        } else { setFail(msg); }
                    }).catch(reason => { setFail(reason); })
                }
            }).catch((reason: any) => {
                console.error(reason); setFail(`发生错误：${reason}`)
            }).finally(() => { setIng(false); })
        }

        return <React.Fragment>
            <AddCircleOutline onClick={() => setVisible(true)} />
            <Popup
                visible={visible}
                onMaskClick={() => { setVisible(false) }}
                destroyOnClose
            >
                <DemoBlock padding={8} title={`${title}`}>
                    <Form
                        layout={'vertical'}
                        onFinish={onFinish}
                        footer={<>
                            {fail !== undefined && <NoticeBar
                                extra={<Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>}
                                content={fail}
                                color='alert'
                            />}
                            <Button block type='submit'
                                disabled={ing || fail !== undefined || success !== undefined}
                                loading={ing}
                                color='primary' size='large'>{success !== undefined ? '已增加' : (fail !== undefined ? '执行失败' : '增加')}</Button></>}
                    >
                        <Form.Item name='materials' label={label} rules={[{ required: true, message: label }]}>
                            <UploadStatus folder={`${url.replace('/','-')}`} />
                        </Form.Item>
                    </Form>
                </DemoBlock>
            </Popup>
        </React.Fragment>
}

